package net.diaowen.dwsurvey.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.dwsurvey.service.UserManager;
import net.diaowen.dwsurvey.service.WechatManager;

@Controller
@RequestMapping("/sy/user/user-admin")
public class UserAdminController{
	protected final static String USER_ROLE="userRole";
	
	protected final static String RESOURCE_PATH = UserAdminController.class.getResource("/template").getPath();
	
	@Autowired
	private AccountManager accountManager;
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private WechatManager wechatManager;

	@RequestMapping("/list.do")
	public ModelAndView list(HttpServletRequest request,Page<User> page,Integer status,String studentId) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		try{
			User entity = new User();
			entity.setStatus(status);
			entity.setStudentId(studentId);
			page=userManager.findPage(page,entity);
			modelAndView.addObject("page",page);
			modelAndView.addObject("status",status);
			modelAndView.addObject("studentId",studentId);
		}catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.setViewName("/diaowen-useradmin/list");
		return modelAndView;
	}

	@RequestMapping("/input.do")
	public ModelAndView input(String id) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		if(id!=null){
			User user = userManager.getModel(id);
			modelAndView.addObject("entity",user);
			modelAndView.addObject("id",id);
		}
		modelAndView.setViewName("/diaowen-useradmin/input");
		return modelAndView;
	}
	

	@RequestMapping("/save.do")
	public String save(User entity) throws Exception {
		try{
			String id = entity.getId();
			if(id==null || id.equals("")){
				entity.setId(null);
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date edate = dateFormat.parse(entity.getEnrollmentTimeStr());
				entity.setEnrollmentTime(edate);
				userManager.adminSave(entity,null);
			}else{
				User user = userManager.get(id);
				user.setEmail(entity.getEmail());
				user.setName(entity.getName());
				user.setStatus(entity.getStatus());
				user.setPwd(entity.getPwd());
				user.setCellphone(entity.getCellphone());
				user.setSchool(entity.getSchool());
				user.setCollege(entity.getCollege());
				user.setMajor(entity.getMajor());
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date edate = dateFormat.parse(entity.getEnrollmentTimeStr());
				user.setEnrollmentTime(edate);
				user.setSex(entity.getSex());
				user.setProvince(entity.getProvince());
				userManager.adminSave(user,null);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return "redirect:/sy/user/user-admin/list.do";
	}

	/**
	 * 账号禁用
	 **/
	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(String id,String event) throws Exception {
		String result="false";
		try{
			if(event!=null && "delete".equals(event)){
				//微信部分先解除绑定，防止绑定失败
				wechatManager.releaseBindByUserId(id);
				userManager.delete(id);

			}else{
				//极限物理删除
				userManager.disUser(id);
			}
			result="true";
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/checkLoginNamelUn.do")
	@ResponseBody
	public String checkLoginNamelUn(String id,String loginName) throws Exception{
		User user=userManager.findNameUn(id,loginName);
		String result="true";
		if(user!=null){
			result="false";
		}
		return result;
	}


	@RequestMapping("/checkEmailUn.do")
	@ResponseBody
	public String checkEmailUn(String id,String email) throws Exception{
		User user=userManager.findEmailUn(id,email);
		String result="true";
		if(user!=null){
			result="false";
		}
		return result;
	}
	
	@RequestMapping("/download.do")
	  public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
      //处理请求  
      //读取要下载的文件  
      File f = new File(RESOURCE_PATH + "import.xls");  
      if(f.exists()){  
      	FileInputStream fis;
          fis = new FileInputStream(f);  
          String filename = URLEncoder.encode(f.getName(),"utf-8"); //解决中文文件名下载后乱码的问题  
          byte[] b = new byte[fis.available()];  
          fis.read(b);  
          response.setCharacterEncoding("utf-8");  
          response.setHeader("Content-Disposition","attachment; filename="+filename+"");  
          //获取响应报文输出流对象  
          ServletOutputStream  out =response.getOutputStream();  
          //输出  
          out.write(b);  
          out.flush();  
          fis.close();
          out.close();  
      }   
	}
	
	@RequestMapping("/import.do")
	public ModelAndView importUser(String id) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		if(id!=null){
			User user = userManager.getModel(id);
			modelAndView.addObject("entity",user);
			modelAndView.addObject("id",id);
		}
		modelAndView.setViewName("/diaowen-useradmin/import");
		return modelAndView;
	}
	
	
	@RequestMapping("/upload.do")
    public ModelAndView upLoad(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
		ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
		String savePath = shiroRequest.getSession().getServletContext().getRealPath("/") + File.separator+"WEB-INF"+File.separator+"upload" + File.separator;
		String fileName = String.valueOf(System.currentTimeMillis()) + ".xls";
		proUpfile((ShiroHttpServletRequest) request, savePath, fileName);
		


        Map<String,Object> resultMap = userManager.doBatchImport(savePath + fileName);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("resultMap",resultMap);
		modelAndView.setViewName("/diaowen-useradmin/result");
		return modelAndView;
    }
	
	
    private String proUpfile(ShiroHttpServletRequest request, String savePath, String fileName) {
        ShiroHttpServletRequest shiroRequest = request;
        StringBuffer sb = new StringBuffer();
        Map<String, String> files = new HashMap<String, String>();

        File dirFile = new File(savePath);
        if  (!dirFile .exists()  && !dirFile .isDirectory()) {
            dirFile .mkdir();
        }
        //创建一个通用的多部分解析器
        try{

            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
            MultipartHttpServletRequest multiRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());

            //CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(shiroRequest.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求

            System.setProperty("sun.jnu.encoding","utf-8");
            //转换成多部分request
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        //定义上传路径
                        String path = savePath + fileName;
                        File localFile = new File(path);
                        file.transferTo(localFile);
                        files.put(fileName, path);
                    }
                }
            }
            if(files.size()>0){
                sb.append("{\"success\":\"true\"");
                sb.append(",\"filename\":\"");

                for (String key: files.keySet()) {
                    sb.append(key);
                    sb.append("  ");
                }
                sb.append("\"");
                sb.append(",\"location\":\"");

                for (String key: files.keySet()) {
                    sb.append(files.get(key) + ";");
                }

                if(sb!=null&& StringUtils.isNotBlank(sb.toString())&&sb.toString().endsWith(";")){
                    sb.deleteCharAt(sb.length()-1);
                }

                sb.append("\"");
                sb.append("}");
            }else{
                sb.append("{\"success\":\"false\",\"error\":\"未收到上传文件\"}");
            }
        }catch (Exception e){
            sb.append("{\"success\":\"false\",\"error\":\"上传失败\"}");
            e.printStackTrace();
        }
        return sb.toString();
    }

}
